import 'package:itoken/Config.dart';
import 'package:itoken/Modle/MAddress.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class HAddress {
  static final HAddress _instance = HAddress.internal();
  factory HAddress() => _instance;
  HAddress.internal();

  static Database _db;

  Future<Database> get db async {
    if (_db != null) {
      return _db;
    }
    _db = await initDb();
    return _db;
  }

  initDb() async {
    var databasesPath = await getDatabasesPath();
    String path = join(databasesPath, 'sqflite.db');
    var ourDb = await openDatabase(path,
        version: Config.dbVersion, onCreate: _onCreate);
    return ourDb;
  }

  //创建数据库表
  void _onCreate(Database db, int version) async {
    await db.execute(MAddress.sql);
    print("Table is created");
  }

  //按照id查询
  Future<MAddress> getItem(String id) async {
    var dbClient = await db;
    var result = await dbClient
        .rawQuery("SELECT * FROM ${MAddress.tableName} WHERE id = $id");
    if (result.length == 0) return null;
    return MAddress.fromMap(result.first);
  }

  //修改
  Future<int> updateItem(MAddress data) async {
    var dbClient = await db;
    return await dbClient.update(MAddress.tableName, data.toMap(),
        where: "id = ?", whereArgs: [data.id]);
  }

  //插入
  Future<int> saveItem(MAddress data) async {
    var dbClient = await db;
    int res = await dbClient.insert(MAddress.tableName, data.toMap());
    return res;
  }

  //查询
  Future<List> getTotalList() async {
    var dbClient = await db;
    var result = await dbClient.rawQuery("SELECT * FROM ${MAddress.tableName}");
    return MAddress.fromMapList(result.toList());
  }

  //清空数据
  Future<int> clear() async {
    var dbClient = await db;
    return await dbClient.delete(MAddress.tableName);
  }

  //根据id删除
  Future<int> deleteItem(int id) async {
    var dbClient = await db;
    return await dbClient
        .delete(MAddress.tableName, where: "id = ?", whereArgs: [id]);
  }

  //关闭
  Future close() async {
    var dbClient = await db;
    return dbClient.close();
  }
}
